package pack0714.cn;

public class MyRun implements Runnable {

    private Person p1;
    private Person p2;

    public MyRun(Person p1, Person p2) {
        this.p1 = p1;
        this.p2 = p2;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        if ("t".equals(name)) {
            synchronized ("p1") {
                System.out.println(Thread.currentThread().getName() + "进入同步块,锁定p1资源");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized ("p2") {
                    System.out.println(Thread.currentThread().getName() + "醒来了,准备锁定p2资源");
                }
            }
        } else {
            synchronized ("p2") {
                System.out.println(Thread.currentThread().getName() + "进入同步块,锁定p2资源");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (p1) {
                    System.out.println(Thread.currentThread().getName() + "醒来了,准备锁定p1资源");
                }
            }
        }
    }
}